#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (head == nullptr) return head;
        ListNode* prev = new ListNode(-1);
        prev->next = head;
        ListNode* cur = head;
        ListNode* next = head;
        while (n--)
        {
            next = next->next;
        }
        while (next != nullptr)
        {
            cur = cur->next;
            next = next->next;
            prev = prev->next;
        }
        if (prev->next == head) return head->next;
        prev->next = cur->next;
        return head;
    }
};